package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    AuthorService authorService;

    @Autowired
    ApArticleConfigService apArticleConfigService;

    @Autowired
    ApArticleContentService apArticleContentService;

    @Autowired
    GeneratePageService generatePageService;

    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    @Override
    public void publishArticle(Integer newsId) {
        //1.根据文章id查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        //2.根据wmNews信息封装ApArticle对象
        ApArticle apArticle = parseApArticle(wmNews);
        System.out.println(apArticle);
        //3.保存或修改apActircle对象
        saveOrUpdateApArticle(apArticle);
        //4.保存配置信息 和 内容信息
        saveConfigAndContent(apArticle,wmNews);
        //5.页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        //6.修改wmNews的状态,将状态改为9，并设置关联的articleId
        updateWmNews(wmNews,apArticle);

        //7. MQ通知es索引库，更新文章索引
    }

    private void updateWmNews(WmNews wmNews,ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程修改自媒体文章状态失败");
        }
    }

    private void saveConfigAndContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());
        config.setIsComment(true);
        config.setIsForward(true);
        config.setIsDown(false);
        config.setIsDelete(false);
        apArticleConfigService.save(config);
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);
    }

    private void saveOrUpdateApArticle(ApArticle apArticle) {
        if (apArticle.getId()==null){
            apArticle.setViews(0);
            apArticle.setLikes(0);
            apArticle.setComment(0);
            apArticle.setCollection(0);
            this.save(apArticle);
        }else {
            apArticleConfigService.remove(
                    Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getArticleId,apArticle.getId())
            );
            apArticleContentService.remove(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId,apArticle.getId())
            );
            this.updateById(apArticle);
        }
    }

    private ApArticle parseApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setLayout(wmNews.getType());
        apArticle.setFlag((byte)0);
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询频道信息失败");
        }
        AdChannel channel = channelResult.getData();
        apArticle.setChannelName(channel.getName());
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;
    }

    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = result.getData();
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)&&!WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章的状态，不是审核通过状态，发布文章失败");
        }

        return wmNews;
    }

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    private String webSite;
    /**
     * 根据参数加载文章列表
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2 执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            // 获取文章封面字段
            String images = article.getImages();
            if (StringUtils.isNotBlank(images)) {
                // 将封面按照,号切割   生成流
                images = Arrays.stream(images.split(","))
                        // 每一个路径添加前缀
                        .map(url -> webSite + url)
                        // 将加了前缀的路径  拼接成字符串
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        return result;
    }
}